<template>
  <div>
    <!-- 查询条件 -->
    <div style="padding: 20px  0 0 60px;">
      <div class="com-title">
        <div class="comt-title-line"></div>
        <span>活动名称：{{ activityData.title }}</span>
        <div class="comt-activity">
          <div>活动开始时间：</div>
          <span>{{ startTime }}</span>
        </div>
        <div class="comt-activity">
          <div>签到人数：</div>
          <span>{{ startPerson }}人</span>
        </div>
        <div class="comt-activity comt-activity-blur">
          <div>签退人数：</div>
          <span>{{ endPerson }}人</span>
        </div>
        <div class="comt-activity">
          <div>活动人数限制：</div>
          <span>{{ activityData.renshu_max }}人</span>
        </div>
        <div class="comt-activity">
          <div>活动积分：</div>
          <span>{{ activityData.jifen_num }}分</span>
        </div>
        <div class="comt-activity">
          <div>活动状态：</div>
          <!-- <span>{{ getStatus }}</span> -->
          <span v-if="activityData.status == '1'" style="color: #409EFF">未开始</span>
          <span v-else-if="activityData.status == '2'" style="color: #67c23a">进行中</span>
          <span v-else-if="activityData.status == '3'" style="color: #f56c6c">已结束</span>
          <span v-else-if="activityData.status == '0'" style="color: #67c23a">申请中</span>
        </div>
      </div>
      <el-form :inline="true" :model="searchForm" ref="searchForm">
        <!-- <el-form-item label="签到/签退执行状态" prop="start_time" class="d2-ml-10">
          <el-radio-group v-model="status" @change="changeStatus">
            <el-radio label="0">自动执行</el-radio>
            <el-radio label="1">手动执行</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item label="开始时间" prop="start_time" class="d2-ml-10">
          <el-date-picker
            v-model="searchForm.start_time"
            align="right"
            type="datetime"
            @change="clear"
            @clear="clear"
            placeholder="请选择开始时间"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time" class="d2-ml-10">
          <el-date-picker
            v-model="searchForm.end_time"
            align="right"
            type="datetime"
            placeholder="请选择结束时间"
            @change="clear"
            @clear="clear"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <!-- <el-button type="primary" @click="onSearch" :disabled="loading">查询</el-button> -->
          <!-- <el-button @click="onReset" :disabled="loading">重置</el-button> -->
          <el-button v-if="activityData.status == '1'" type="primary" @click="startActivity">开始活动</el-button>
          <el-button v-if="activityData.status == '2'" type="info">已开始</el-button>
          <el-button v-if="activityData.status == '2'" type="primary" @click="endActivity">结束活动</el-button>
          <el-button v-if="activityData.status == '3'" type="info" @click="endActivityInfo">已结束</el-button>
          <el-button type="primary" @click="repairActivity">补录老人</el-button>
          <el-button type="primary" @click="getStatusList">状况记录列表</el-button>
        </el-form-item>
      </el-form>
    </div>
     <el-divider></el-divider>
     <div style="padding: 10px  40px 0 40px;">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" v-for="(item, index) in list" :key="index">
        <div class="riactivity-item">
          <div class="riactivity-img">
              <img :src="item.image" alt="">
          </div>
          <div class="riactivity-content">
            <div class="riactivity-name">
              姓名：<span>{{item.name}}</span> <span v-if="item.tiwen">{{ item.tiwen }}<span v-if="parseFloat(item.tiwen)">℃</span></span>
            </div>
            <div class="riactivity-name">
              地址：<span>{{ item.address }}</span>
            </div>
            <div class="riactivity-name">
              签到时间：<span>{{ item.start_time | getTime }}</span>
            </div>
            <div v-if="item.end_time" class="riactivity-name">
              签退时间：<span>{{ item.end_time | getTime }}</span>
            </div>
            <div class="riactivity-btn">
              <el-button type="info">已签到</el-button>
              <el-button v-if="item.status == 2" type="info">已签退</el-button>
              <el-button v-if="item.status != 2"  @click="signoutClick(item)" type="primary">签退</el-button>
            </div>
            <el-button type="text" class="button-edit-color detail-edit-button" @click="edit(item)"><i class="fa fa-edit" aria-hidden="true"></i> 状况记录</el-button>
          </div>
        </div>
      </el-col>
      <div class="nodata_img" v-if="list.length == 0">
        <img src="@/assets/no_data1.png" alt="">
        暂无数据
      </div>
    </el-row>
    </div>
    <!--添加弹窗-->
    <el-dialog
      title="补录签到"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false">
      <activity-repair @cancle="dialogVisible = false" :aid="acid" @load="load"></activity-repair>
    </el-dialog>
    <!--添加弹窗-->
    <el-dialog
      title="老人当日状况记录"
      v-if="dialogRecordVisible"
      :visible.sync="dialogRecordVisible"
      width="800px"
      :close-on-click-modal="false">
      <status-records @cancle="dialogRecordVisible = false" :data="statusdata" @load="load"></status-records>
    </el-dialog>
    <!-- 查看记录 -->
    <el-drawer title="网点列表" :with-header="false" size="70%" :visible.sync="dialogActivityVisible" :destroy-on-close="true" @close="dialogActivityVisible = false" :wrapperClosable="false" direction="rtl">
      <activity-list @close="dialogActivityVisible = false" :list="list"></activity-list>
    </el-drawer>
  </div>
</template>

<script>
import * as APIDailycare from '@/api/dailycare'
import { sex, age, elderlyCategory, sourceType, unixToDate } from "@/utils";
import { mapState } from 'vuex'
import activityRepair from './components/activity-repair'
import statusRecords from './components/status-records'
import activityList from './components/activity-list'
export default {
  name: 'dailycare-activity-detail',
  components: {
    activityRepair,
    statusRecords,
    activityList
  },
  computed: {
    /* ...mapState('d2admin/user', [
      'info'
    ]), */
    ...mapState('facewebsocket', [
      'deviceMsg',
      'sendFaceMsg'
    ])
  },
  data () {
    return {
      dialogActivityVisible: false,
      startTime: '',
      // 当日状况记录
      dialogRecordVisible: false,
      // 补录老人签到
      dialogVisible: false,
      searchForm: {
        page: 1
      },
      activityData: {},
      acid: '',
      loading: false,
      list: [],
      status: '0',
      startPerson: 0,
      endPerson: 0,
      form: {
        address: '',
        tiwen: '',
        name: '',
        image: '',
        oid: '',
        a_id: ''
      },
      data: {},
      statusdata: {}
    }
  },
  filters: {
    getTime (value) {
      return unixToDate(value)
    }
  },
  created () {
    this.acid = this.$route.query.id || ''
    this.form = { ...this.form, ...{ a_id: this.acid } }
  },
  mounted () {
    this.fetchTableList()
    this.getActivity()
  },
  watch: {
    deviceMsg: {
      handler: function (newVal) {
        this.init(newVal, this)
      }
    }
  },
  methods: {
    getStatusList () {
      this.dialogActivityVisible = true
    },
    edit (row) {
      this.dialogRecordVisible = true
      this.statusdata = { ...{ name: row.name, tiwen: row.tiwen, id: row.id, yinshi: row.yinshi, fuyao: row.fuyao, jibin: row.jibin } }
    },
    clear () {
      this.fetchTableList({ page: 1 })
    },
    changeStatus (status) {
      APIDailycare.riusersZidong({ status }).then(() => {
        this.status = status
      })
    },
    init (data, _that) {
      /* const { info } = _that
      let device_sn = ''
      if (info.face && info.face.length !== 0) {
        info.face.forEach(item => {
          if (item.type === '1') {
            device_sn = item.device_sn || ''
          }
        })
      } */
      let device_sn = ''
      let userinfo = localStorage.getItem("userdata") || {}
      if(userinfo) {
      	userinfo = JSON.parse(userinfo);
        if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
            userinfo.facedev.forEach(item => {
               device_sn = item.device_sn || ''
            })
        }
      }
      if (data.route == 'face') {
        if (device_sn == data.data.device_sn) {
          if (data.data.match) {
            if (_that.activityData.status == '2') {
              const matchObj = data.data.match
              const personObj = data.data.person
              const closeup_pic = data.data.closeup_pic
              const personImg = closeup_pic.format == 'jpg' ? 'data:image/jpeg;base64,' + closeup_pic.data : closeup_pic.format == 'png' ? 'data:image/png;base64,' + closeup_pic.data : 'data:image/jpeg;base64,' + closeup_pic.data
              const tiwenText = personObj.temperatur ? personObj.temperatur.toFixed(1) : '体温检测失败'
              _that.form = {
                ..._that.form,
                ...{
                  address: matchObj.customer_text,
                  tiwen: tiwenText,
                  name: matchObj.person_name,
                  image: personImg,
                  oid: matchObj.person_id,
                  a_id: _that.acid
                }
              }
              _that.getRiusersQianinfo(matchObj.person_id, tiwenText)
              _that.sendMsgFace('比对成功')
            } else {
              _that.$message.error('检测到人脸，活动还未开始，请先开始活动')
              _that.sendMsgFace('检测到人脸，活动还未开始，请先开始活动')
            }
          } else {
            _that.$message.error('人脸库没有该人员, 请先录入')
            _that.sendMsgFace('人脸库没有该人员, 请先录入')
          }
        }
      }
    },
    // 获取签到信息
    getRiusersQianinfo (oid, tiwen) {
      APIDailycare.riusersQianinfo({
        oid: oid,
        a_id: this.acid
      }).then(res => {
        const data = res.data;
        const orderInfo = data.order || ''
        const activityInfo = data.activity || {}
        if (orderInfo && orderInfo.status == '1') { // 已签到
          const jifen_type = activityInfo.jifen_type
          const jifen_num = activityInfo.jifen_num || 0
          let jifen_text = 0
          const time = this.dateToUnix(this.getNowFormatDate()) - Number(orderInfo.start_time)
          const timeNum = Math.floor(time / 3600)
          if (jifen_type == '1') {
            jifen_text = jifen_num
          } else if (jifen_type == '2') {
            jifen_text = jifen_num * timeNum
          }
          const end_time = this.getNowFormatDate()
          this.postRiusersQiantui(jifen_text, end_time, orderInfo.id)
        } else if (!orderInfo || orderInfo.status == '2') { // 已签退
          this.postRiusersQiandao(oid, tiwen)
        }
      })
    },
    // 签到
    postRiusersQiandao (oid, tiwen) {
      APIDailycare.riusersQiandao({
        a_id: this.acid,
        oid: oid,
        tiwen: tiwen
      }).then(res => {
        this.$message.success('签到成功')
        this.fetchTableList()
        this.sendMsgFace('签到成功')
      }).catch(() => {
        this.$message.error('签到失败')
        this.sendMsgFace('签到失败')
      })
    },
    sendMsgFace (text) {
      /* const { info } = this
      let device_sn = ''
      if (info.face && info.face.length !== 0) {
        info.face.forEach(item => {
          if (item.type === '1') {
            device_sn = item.device_sn || ''
          }
        })
      } */
      let device_sn = ''
      let userinfo = localStorage.getItem("userdata") || {}
      if(userinfo) {
      	userinfo = JSON.parse(userinfo);
        if(userinfo.hasOwnProperty('facedev') && userinfo.facedev.length != 0){
            userinfo.facedev.forEach(item => {
               device_sn = item.device_sn || ''
            })
        }
      }
      if (device_sn) {
        const senddata = {
          cmd: 'send_dev',
          device_sn: device_sn,
          data: {
            cmd: 'tts play',
            text: text
          }
        }
        this.$face.$ws.send(JSON.stringify(senddata))
      }
    },
    // 签退
    postRiusersQiantui (jifen, end_time, id) {
      APIDailycare.riusersQiantui({
        jifen: jifen,
        end_time: end_time,
        id: id
      }).then(res => {
        this.$message.success('签退成功')
        this.fetchTableList()
        this.sendMsgFace('签退成功')
      }).catch(() => {
        this.$message.error('签退失败')
        this.sendMsgFace('签退失败')
      })
    },
    signoutClick (row) {
      this.getRiusersQianinfo(row.oid, row.tiwen)
    },
    // 开始活动
    startActivity () {
      APIDailycare.riactivityStart({ status: 2, id: this.acid }).then(() => {
        this.fetchTableList()
        this.getActivity()
      })
    },
    // 结束活动
    endActivity () {
      APIDailycare.riactivityStart({ status: 3, id: this.acid }).then(() => {
        this.fetchTableList()
        this.getActivity()
      })
    },
    // 活动已结束
    endActivityInfo () {
      this.$message({
        message: '活动已结束，开始新活动请重新创建',
        type: 'warning',
        duration: 4000
      })
      this.sendMsgFace('活动已结束，开始新活动请重新创建')
    },
    // 补录老人
    repairActivity () {
      this.dialogVisible = true
    },
    // 获取当前系统时间
    getNowFormatDate () {
      const date = new Date()
      const seperator1 = '-'
      const seperator2 = ':'
      let month = date.getMonth() + 1
      let strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      const currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + ' ' + date.getHours() + seperator2 + date.getMinutes() + seperator2 + date.getSeconds()
      return currentdate
    },
    /** 将时间改为unix格式 */
    dateToUnix (date) {
      let newStr = date.replace(/:/g, '-')
      newStr = newStr.replace(/ /g, '-')
      const arr = newStr.split('-')
      const datum = new Date(Date.UTC(
        arr[0],
        arr[1] - 1,
        arr[2],
        arr[3] - 8 || -8,
        arr[4] || 0,
        arr[5] || 0
      ))
      return parseInt(datum.getTime() / 1000)
    },
    getActivity () {
      APIDailycare.riusersActivity({ id: this.acid }).then((res) => {
        if (res.code == 200) {
          const { activity = {} } = res.data
          this.activityData = activity
          this.status = res.zidong
          this.startTime = unixToDate(activity.start_time)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    add () {
      this.dialogVisible = true
      this.data = {}
    },
    load () {
      this.fetchTableList()
    },
    // 获取数据
    fetchTableList (pageObj) {
      this.loading = true
      this.searchForm = {
        ...this.searchForm,
        ...pageObj,
        ...{ id: this.acid }
      }
      APIDailycare.riusersList(this.searchForm).then((res) => {
        if (res.code == 200) {
          const { list = [] } = res.data;
          this.list = list || []
          let startPerson = 0
          let endPerson = 0
          list.forEach(item => {
            if (item.status === '1') {
              startPerson++
            } else if (item.status === '2') {
              startPerson++
              endPerson++
            }
          })
          this.startPerson = startPerson
          this.endPerson = endPerson
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 点击”查询“按钮 => 此时缓存查询参数
    onSearch () {
      this.fetchTableList()
    },
    // 重置
    onReset () {
      this.$refs.searchForm.resetFields()
      this.fetchTableList()
    }
  }
}
</script>

<style lang="scss">
.el-cascader{
  width: 100%;
}
.task-list-img {
  width: 40px;
  height: 40px;
}
.tag-cursor {
  cursor: pointer;
}
.riactivity-item img {
  width: 120px;
  height: 160px;
}
.riactivity-item {
  display: flex;
  border: 1px solid #DFE2E9;
  padding: 10px;
  align-items: center;
  height: 200px;
  margin-bottom: 15px;
  position: relative;
}
.detail-edit-button {
  position: absolute;
  right: 20px;
  top: 7px;
}
.riactivity-name {
  font-size: 14px;
  text-align: left;
  width: 100%;
  height: 32px;
  line-height: 32px;
}
.riactivity-content {
  margin-left: 10px;
  flex: 1;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.com-title {
  position: relative;
  color: #333;
  font-size: 20px;
  font-weight: 700;
  display: flex;
  margin-bottom: 15px;
}

.comt-activity{
  display: flex;
  align-items: center;
  margin-left: 40px;
  font-size: 14px;
  color: #487eea;
}

.comt-activity-blur {
  color: #ec5237;
}
.nodata_img {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 20px;
  color: #bfcbd9;
  margin-top: 40px;
  img {
    width: 200px;
    height: 200px;
    margin-bottom: 20px;
  }
}
</style>
